package com.yami.shop.webservice.api.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.CopyrightWorksService;
import com.yami.shop.service.UserCopyrightService;
import com.yami.shop.service.UserService;
import com.yami.shop.webservice.common.model.*;
import com.yami.shop.webservice.common.service.CopyrightService;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;


/**
 *
 * @ClassName:
 * @Description: 版权登记
 * @Author:
 * @Date: 2
 * @History 修改描述
 */
@RestController
@RequestMapping(value = "/copyright")
public class CopyrightController {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private CopyrightService copyrightService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserCopyrightService userCopyrightService;
	@Autowired
	private CopyrightWorksService copyrightWorksService;
	/**
	 * 商户登记存证注册
	 * @param
	 * @return
	 */
	@GetMapping("/foreign")
	public ServerResponseEntity foreign() {
		String userId = SecurityUtils.getUser().getUserId();
		User byUserId = userService.getUserByUserId(userId);
		if(ObjectUtil.isNull(byUserId.getRealName())){
			return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.check.realname"));
		}
		try {
			UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
			RegisterForeignDto foreignDto = new RegisterForeignDto();
			if(ObjectUtil.isNull(userCopyright)){
				//保存本地
				userCopyright = new UserCopyright();
				userCopyright.setUserId(userId);
				userCopyright.setCreateTime(new Date());
				userCopyrightService.save(userCopyright);
				//商户登记存证注册
				foreignDto.setName(byUserId.getRealName());
				foreignDto.setNumber(byUserId.getIdNumber());
				foreignDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
				copyrightService.foreign(foreignDto);
			}
			return  ServerResponseEntity.success(userCopyright.getPlatformUserId());
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 文件上传
	 * @param attachmentUploadDto
	 * @return
	 */
	@PostMapping("/fileUpload")
	public ServerResponseEntity fileUpload(AttachmentUploadDto attachmentUploadDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		try {
			attachmentUploadDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
			File file = getFile(attachmentUploadDto.getFile());
			JSONObject jsonObject = copyrightService.fileUpload(attachmentUploadDto, file);
			if(file.exists()){
				file.delete();
			}
			return  ServerResponseEntity.success(jsonObject);
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 新增著作权人
	 * @param ownerDto
	 * @return
	 */
	@PostMapping("/addOwner")
	public ServerResponseEntity addOwner(@RequestBody @Validated OwnerDto ownerDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		try {
			ownerDto.setSignature(ownerDto.getSignature());
			ownerDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
			JSONObject jsonObject = copyrightService.addOwner(ownerDto);
			userCopyright.setOwnerId(Integer.valueOf(jsonObject.getString("id")));
			userCopyright.setOwnerName(ownerDto.getOwnerName());
			userCopyright.setIdNo(ownerDto.getIdNo());
			userCopyrightService.updateById(userCopyright);
			return  ServerResponseEntity.success();
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 查询著作权人列表
	 * @param ownersListDto
	 * @return
	 */
	@GetMapping("/getOwnersList")
	public ServerResponseEntity getOwnersList(@Validated OwnersListDto ownersListDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		try {
			ownersListDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
			return  ServerResponseEntity.success(copyrightService.getOwnersList(ownersListDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 查询通过id著作权人
	 * @param ownersByIdDto
	 * @return
	 */
	@GetMapping("/getOwnersById")
	public ServerResponseEntity getOwnersById(@Validated OwnersByIdDto ownersByIdDto) {
		try {
			String userId = SecurityUtils.getUser().getUserId();
			UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
			if(ObjectUtil.isNull(userCopyright)){
				throw new YamiShopBindException("没有注册用户");
			}
			ownersByIdDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
			ownersByIdDto.setOwnerId(Long.valueOf(userCopyright.getOwnerId()));
			return  ServerResponseEntity.success(copyrightService.getOwnersById(ownersByIdDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}


	/**
	 * 字典查询
	 * @param dictItemDto
	 * @return
	 */
	@GetMapping("/dict")
	public ServerResponseEntity getDictByType(@Validated DictItemDto dictItemDto) {
		try {
			return  ServerResponseEntity.success(copyrightService.getDictByType(dictItemDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-新增登记作品信息
	 * @param worksInstDto
	 * @return
	 */
	@PostMapping("/workSave")
	public ServerResponseEntity workSave(@RequestBody @Validated WorksInstDto worksInstDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		worksInstDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		worksInstDto.setAuthorName(userCopyright.getOwnerName());
		worksInstDto.setAuthorSign(userCopyright.getOwnerName());
		try {
			//上传文件

			JSONObject jsonObject = copyrightService.workSave(worksInstDto);
			CopyrightWorks copyrightWorks = new CopyrightWorks();
			copyrightWorks.setWorksName(worksInstDto.getWorksName());
            copyrightWorks.setCreateTime(new Date());
			copyrightWorks.setUserId(userId);
			copyrightWorks.setAcceptanceNumber(jsonObject.getString("acceptanceNumber"));
			copyrightWorksService.save(copyrightWorks);
			return  ServerResponseEntity.success();
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-更新登记作品信息
	 * @param worksInstDto
	 * @return
	 */
	@PostMapping("/workUpdate")
	public ServerResponseEntity workUpdate(@RequestBody @Validated WorksInstDto worksInstDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		worksInstDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		worksInstDto.setAuthorName(userCopyright.getOwnerName());
		worksInstDto.setAuthorSign(userCopyright.getOwnerName());
		try {
			copyrightService.workUpdate(worksInstDto);
			LambdaUpdateWrapper<CopyrightWorks> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
			lambdaUpdateWrapper.eq(CopyrightWorks::getAcceptanceNumber,worksInstDto.getAcceptanceNumber());
			lambdaUpdateWrapper.set(CopyrightWorks::getUpdateTime,new Date());
			copyrightWorksService.update(lambdaUpdateWrapper);
			return  ServerResponseEntity.success();
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-查询登记作品列表
	 * @param workInstPageQueryDto
	 * @return
	 */
	@GetMapping("/workPage")
	public ServerResponseEntity getWorksInstPage(@Validated WorkInstPageQueryDto workInstPageQueryDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workInstPageQueryDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.getWorksInstPage(workInstPageQueryDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-根据受理号查询登记作品 是返回整个作品的详细信息，包括你们登记的作品的全量信息
	 * @param workByAcceptNoDto
	 * @return
	 */
	@GetMapping("/getWorkByAcceptNo")
	public ServerResponseEntity getWorkByAcceptNo(@Validated WorkByAcceptNoDto workByAcceptNoDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workByAcceptNoDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.getWorkByAcceptNo(workByAcceptNoDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-根据受理号查询审核进度
	 * @param workByAcceptNoDto
	 * @return
	 */
	@GetMapping("/getWorkProgressByAcceptNo")
	public ServerResponseEntity getWorkProgressByAcceptNo(@Validated WorkByAcceptNoDto workByAcceptNoDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workByAcceptNoDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.getWorkProgressByAcceptNo(workByAcceptNoDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-下载作品存证证书
	 * @param workByAcceptNoDto
	 * @return
	 */
	@GetMapping("/worksEvidence")
	public ServerResponseEntity depositWorksCertificate(@Validated WorkByAcceptNoDto workByAcceptNoDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workByAcceptNoDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.depositWorksCertificate(workByAcceptNoDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-下载作品登记证书
	 * @param workByAcceptNoDto
	 * @return
	 */
	@GetMapping("/worksRegistration")
	public ServerResponseEntity registrationWorksCertificate(@Validated WorkByAcceptNoDto workByAcceptNoDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workByAcceptNoDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.registrationWorksCertificate(workByAcceptNoDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}

	/**
	 * 登记-获取作品登记数据 是返回作品的概要信息，仅有名称和证书这些
	 * @param workByAcceptNoDto
	 * @return
	 */
	@GetMapping("/worksRegistrationData")
	public ServerResponseEntity worksRegistrationData(@Validated WorkByAcceptNoDto workByAcceptNoDto) {
		String userId = SecurityUtils.getUser().getUserId();
		UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, userId).eq(UserCopyright::getStatus, 1));
		if(ObjectUtil.isNull(userCopyright)){
			throw new YamiShopBindException("没有注册用户");
		}
		workByAcceptNoDto.setPlatformUserId(String.valueOf(userCopyright.getPlatformUserId()));
		try {
			return  ServerResponseEntity.success(copyrightService.worksRegistrationData(workByAcceptNoDto));
		}catch (Exception e){
			 throw new YamiShopBindException(e.getMessage());
		}
	}
	/**
	 * MultipartFileUtil 转File
	 *
	 * @param multipartFile
	 * @return
	 */
	public static File getFile(MultipartFile multipartFile) {
		String fileName = multipartFile.getOriginalFilename();
		File file = new File(fileName);
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			byte[] ss = multipartFile.getBytes();
			for (byte s : ss) {
				out.write(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
//        File f = new File(file.toURI());
//        if (f.delete()) {
//            System.out.println("删除成功");
//        } else {
//            System.out.println("删除失败");
//        }
		return file;
	}
	@GetMapping("/page")
	@Operation(summary =  "分页查询", description = "分页查询")
	public ServerResponseEntity<IPage<CopyrightWorks>> getNoticePage(PageParam<CopyrightWorks> page, CopyrightWorks copyrightWorks) {
		String userId = SecurityUtils.getUser().getUserId();
		IPage<CopyrightWorks> noticePage = copyrightWorksService.page(page, new LambdaQueryWrapper<CopyrightWorks>()
				.eq(StrUtil.isNotEmpty(copyrightWorks.getStatus()) , CopyrightWorks::getStatus, copyrightWorks.getStatus())
				.eq(CopyrightWorks::getUserId, userId)
				.eq(StrUtil.isNotEmpty(copyrightWorks.getWorksName()) , CopyrightWorks::getWorksName, copyrightWorks.getWorksName()).orderByDesc(CopyrightWorks::getCreateTime));
		return ServerResponseEntity.success(noticePage);
	}
}

